//
//  iapLayer.m
//  fishGame
//
//  Created by Charles How on 12-4-17.
//  Copyright 2012年 hust. All rights reserved.
//

#import "iapLayer.h"
#import "storage.h"
#import "GameMusicSetting.h"


NSString * iap_fun_name_array[]=
{
    @"Get 1000 coins",
    @"Get 5000 coins",
    @"Get 10000 coins",
    @"Upgrade 1 level",
    @"Upgrade 3 level",
    @"Upgrade 10 level",
};

@implementation iapLayer


@synthesize activityIndicatorView;


-(id) init
{
	if( (self=[super init]) ) {
		
		
        
		//init array
		menuItemArray=[[NSMutableArray alloc] init];
		
		CGSize s = [[CCDirector sharedDirector] winSize];
		
		//bg
		CCSprite * bg=[CCSprite spriteWithFile:@"bgblur01_01.png"];
		bg.position=ccp(s.width/2,s.height/2);
		[self addChild:bg z:0 tag:100];
		
        
        /*
		//board
		
		CCSprite * board=[CCSprite spriteWithFile:@"button_other_003.png"];
		board.position=ccp(s.width/2,s.height/2);
		[self addChild:board];
		
		//////title
		CCLabelTTF *title = [CCLabelTTF labelWithString:@"Welcome to Shop"  
											   fontName:@"Marker Felt" 
											   fontSize:20];
		title.position = ccp(s.width/2-s.width/10, s.height-45);
		[self addChild:title];
		
		id jump = [CCJumpBy actionWithDuration:3 position:ccp(s.width/10*2,0) height:0 jumps:4];
		[title runAction: [CCRepeatForever actionWithAction:
						   [CCSequence actions: jump, [jump reverse], nil]
						   ]
		 ];
		
		
		///////iap menus begin
		[CCMenuItemFont setFontName: @"Marker Felt"];
		[CCMenuItemFont setFontSize:27];
		
		CCMenuItemFont *item1 = [CCMenuItemFont itemFromString: @"get 1000 coins" 
														target:self selector:@selector(menuCallback1:)];
		item1.color=ccc3(255, 0, 0);
		
		CCMenuItemFont *item2 = [CCMenuItemFont itemFromString: @"get 5000 coins" 
														target:self selector:@selector(menuCallback2:)];
		
        item2.color=ccc3(0, 255, 0);
        
		CCMenuItemFont *item3 = [CCMenuItemFont itemFromString: @"get 10000 coins" 
														target:self selector:@selector(menuCallback3:)];
		item3.color=ccc3(0, 0, 255);
		
		CCMenuItemFont *item4 = [CCMenuItemFont itemFromString: @"up 1 grade" 
														target:self selector:@selector(menuCallback4:)];
		item4.color=ccc3(255, 0, 0);
        
		CCMenuItemFont *item5 = [CCMenuItemFont itemFromString: @"up 3 grade" 
														target:self selector:@selector(menuCallback5:)];
		item5.color=ccc3(0, 255, 0);
		
		
		CCMenuItemFont *item6 = [CCMenuItemFont itemFromString: @"up 10 grade" 
														target:self selector:@selector(menuCallback6:)];
		item6.color=ccc3(0, 0, 255);
		//CCMenu *menu = [CCMenu menuWithItems: item1, item2,item3,item4,nil];	
		//menu.position = ccp(0,0);
		
		
		[menuItemArray addObject:item1];  //index 0
		[menuItemArray addObject:item2];  //index 1
		[menuItemArray addObject:item3];  //index 0
		[menuItemArray addObject:item4];  //index 1
		[menuItemArray addObject:item5];  //index 0
		[menuItemArray addObject:item6];  //index 1		
		
		assert([menuItemArray count] <= IAP_MENU_ITEM_IAP_MAX);
		
		CCMenu *menu = [CCMenu menuWithItems:
						item1, 
						item2,
						item3,
						item4,
						item5,
						item6,
						nil]; // 4 items.
		
		[menu alignItemsVertically];

		
        
		
        
        
		
        
		id spin1 = [CCRotateBy actionWithDuration:3 angle:360];
		id spin2 = [[spin1 copy] autorelease];
		id spin3 = [[spin1 copy] autorelease];
		
		//[item1 runAction: [CCRepeatForever actionWithAction:spin1]];
		//[item2 runAction: [CCRepeatForever actionWithAction:spin2]];
		//[item3 runAction: [CCRepeatForever actionWithAction:spin3]];
        
		[self addChild:menu z:1 tag:IAP_MENU_TAG];
		
         */
		
        [self addBoardsBG];
		[self addBackButton];
		[self addPicAndLabels];
        
        
		[self initPurchasedItem];
        
        
        [self addAdBg];
        

	}
	
	return self;
}


-(void)addAdBg
{
    //bg
    CGSize s=[[CCDirector sharedDirector] winSize];
    
    CCSprite * ad_bg=[CCSprite spriteWithFile:@"ad-bg.png"];
    ad_bg.position=ccp(s.width/2,ad_bg.contentSize.height/2);
    [self addChild:ad_bg z:0 tag:1001];
    ad_bg.visible=false;
}


-(void)addBoardsBG
{
    CGSize s=[[CCDirector sharedDirector] winSize];
    
    NSString * path=[storage dataFilePathInResource:@"sw-list-board.png"];
    UIImage* image=[UIImage imageWithContentsOfFile:path];
    float scale=s.width/IAP_MAX_COLS/image.size.width;
    UIImage* image2=[self resizeImage:image andScaleX:scale andScaleY:scale];
    
    
    
    
    for (int i=0; i<IAP_MAX_ROWS*IAP_MAX_COLS; i++) {
        CCSprite* board=[CCSprite spriteWithCGImage:image2.CGImage key:@"BOARD_PIC"];
        CCSprite* board2=[CCSprite spriteWithCGImage:image2.CGImage key:@"BOARD_PIC_H"];
        board2.color=ccc3(255, 255, 0);
        
        CCMenuItemSprite *item1 = [CCMenuItemSprite itemFromNormalSprite:board
                                                          selectedSprite:board2
                                                                  target:self selector:@selector(menuCallback_iap:)];
        //item1.color=ccc3(255, 0, 0);
        
        /*
         CCMenuItemFont *item2 = [CCMenuItemFont itemFromString: item.name 
         target:self selector:@selector(menuCallback_Link:)];
         item2.color=ccc3(0, 255, 0);
         */
        
        [menuItemArray addObject:item1];  //index 0
    }
    
    //[menuItemArray addObject:item2];  //index 1
    
    
    assert([menuItemArray count] <= IAP_MAX_COUNT_PER_PAGE);
    
    menu = [CCMenu menuWithItems:
            [menuItemArray objectAtIndex:0], 
            [menuItemArray objectAtIndex:1],
            [menuItemArray objectAtIndex:2], 
            [menuItemArray objectAtIndex:3],
            [menuItemArray objectAtIndex:4], 
            [menuItemArray objectAtIndex:5],
            nil]; // 4 items.
    
    //[menu alignItemsVertically];
    
    [menu alignItemsInColumns:
     [NSNumber numberWithUnsignedInt:IAP_MAX_COLS],
     [NSNumber numberWithUnsignedInt:IAP_MAX_COLS],
     //[NSNumber numberWithUnsignedInt:1],
     //[NSNumber numberWithUnsignedInt:1],
     
     nil
     ]; 
    
    
    
    
    
    
    
    
    id spin1 = [CCRotateBy actionWithDuration:3 angle:360];
    id spin2 = [[spin1 copy] autorelease];
    id spin3 = [[spin1 copy] autorelease];
    
    //[item1 runAction: [CCRepeatForever actionWithAction:spin1]];
    //[item2 runAction: [CCRepeatForever actionWithAction:spin2]];
    //[item3 runAction: [CCRepeatForever actionWithAction:spin3]];
    
    //menu.anchorPoint=ccp(0.0,0.0);
    menu.position=ccp(menu.contentSize.width/2
                      , s.height-menu.contentSize.height/2);
    int width=menu.contentSize.width;
    int height=menu.contentSize.height;
    [self addChild:menu z:1 ];
    
    int i=0;
    for( CCNode *child in [menu children] ) {
        
        ///修正某些菜单的位置
        child.position=ccp(child.position.x-20,child.position.y);
        
        if (i>=0 && i<=2) {
            child.position=ccp(child.position.x,child.position.y+12);
        }
        else if (i>=3 && i<=5) {
            child.position=ccp(child.position.x,child.position.y+40);
        }
        
        i++;
    }
}


-(void)addBackButton
{
    // Image Item  ,back button
    CCSprite * tmpSprite=[CCSprite spriteWithFile:@"menu_quit0.png"];
    CGSize winSize=[[CCDirector sharedDirector] winSize];
    back = [CCMenuItemImage 
            itemFromNormalImage:@"menu_quit0.png" 
            selectedImage:@"menu_quit1.png" 
            target:self 
            selector:@selector(backCallback:)];
    CCMenu *menuBack = [CCMenu menuWithItems:
                        back,nil];
    [menuBack alignItemsHorizontally];
    menuBack.position=ccp(winSize.width-tmpSprite.contentSize.width/2,tmpSprite.contentSize.height/2); ///右下角
    [self addChild: menuBack z:1 tag:IAP_BACK_TAG];
}




-(void)addPicAndLabels
{
    
    
    for (int i=0; i<IAP_MAX_COUNT_PER_PAGE; i++) {
        //清除上次显示的内容
        if ([self getChildByTag:IAP_SPRITE_TAG_PIC_START+i] != nil) {
            [self removeChildByTag:IAP_SPRITE_TAG_PIC_START+i cleanup:YES];
        }
        
        if ([self getChildByTag:IAP_SPRITE_TAG_LAB_START+i] != nil) {
            [self removeChildByTag:IAP_SPRITE_TAG_LAB_START+i cleanup:YES];
        }
    }
    
    
    

    
    
    
    int i=0;
    for( CCNode *child in [menu children] ) {
        
        int curIndex=i;
        
        NSString * image_name=[NSString stringWithFormat:@"iap-show%d.png",curIndex];
        NSString * image_path=[storage dataFilePathInResource:image_name];
        
        ////将NSData中图象数据转换位精灵图象
        UIImage* image=[UIImage imageWithContentsOfFile:image_path];
        
        
        int oriW=image.size.width;
        int oriH=image.size.height;
        float scale=child.contentSize.width/2/oriW;
        
        //UIImage* imageSmall=[self scaleAndRotateImage:image xScale:0.5 yScale:0.5];
        UIImage* image2=[self resizeImage:image andScaleX:scale andScaleY:scale];
        NSString * index_str=[NSString stringWithFormat:@"IAP_ITEM_PIC_%d",curIndex];
        CCSprite* spt=[CCSprite spriteWithCGImage:image2.CGImage key:index_str];
        
        spt.position=ccp(menu.position.x+child.position.x,menu.position.y+child.position.y);
        [self addChild:spt z:10 tag:IAP_SPRITE_TAG_PIC_START+i];
        
        NSString * fontName=[NSString stringWithString:@"Marker Felt"];  //@"Marker Felt"
        CCLabelTTF * label=[CCLabelTTF labelWithString:iap_fun_name_array[i] fontName:fontName fontSize:16];
        label.position=ccp(spt.position.x, 
                           spt.position.y-spt.contentSize.height/2-label.contentSize.height/2);
        if (i<3) {
            label.color=ccc3(0, 255, 0);
        }
        else{
            label.color=ccc3(0, 255, 255);
        }
        [self addChild:label z:10 tag:IAP_SPRITE_TAG_LAB_START+i];
        
        i++;
    }
}





- (void) dealloc
{
	[menuItemArray release];
	[super dealloc];
}



-(void)initPurchasedItem
{
	//////////////////////
	///////一定要设置代理对象的实例，为该对象，否则productAPurchased不会被回调
	///////一定要设置代理对象的实例，为该对象，否则productAPurchased不会被回调
	[MKStoreManager sharedManager].delegate = self;
	
	////////iap check
	/*
     CCLOG(@"c>>>>>11111");
     if ([MKStoreManager featureAPurchased])
     {
     CCLOG(@"c>>>>>111110");
     [AdViewController setRemoveAdState:true];
     }
     
     CCLOG(@"c>>>>>22222");
     if ([MKStoreManager featureBPurchased])
     {
     CCLOG(@"c>>>>>222220");
     [Layer3 setUnlockState:true];
     }
     */
	//////////////////////
}


#pragma mark iap button call back

-(void)menuCallback_iap: (id) sender
{
    [GameMusicSetting playButtonClickEffect];
    
    
    int i=0;
    for( CCNode *child in [menu children] ) {
        
        if (sender == child) {
            break;
        }
        
        i++;
    }
    
    
    int index= i;
    
    switch (index) {
        case 0:
            [self menuCallback1:sender];
            break;
  
        case 1:
            [self menuCallback2:sender];
            break;
            
        case 2:
            [self menuCallback3:sender];
            break;
            
            
        case 3:
            [self menuCallback4:sender];
            break;
            
        case 4:
            [self menuCallback5:sender];
            break;
            
        case 5:
            [self menuCallback6:sender];
            break;
            
        default:
            break;
    }
    
}

-(void) nullCallback: (id) sender
{
	//[(CCLayerMultiplex*)parent_ switchTo:0];
}

-(void) menuCallback1: (id) sender
{
	[self featureAButtonPressed];
}

-(void) menuCallback2: (id) sender
{
	NSLog(@"featureBButtonPressed");
	[self featureBButtonPressed];
}

-(void) menuCallback3:(id) sender
{
	[self featureCButtonPressed];
}

-(void) menuCallback4:(id) sender
{
	[self feature1ButtonPressed];
}

-(void) menuCallback5:(id) sender
{
	[self feature2ButtonPressed];
}

-(void) menuCallback6:(id) sender
{
	[self feature3ButtonPressed];
}


-(void) backCallback: (id) sender
{
	//back to game
	[[CCDirector sharedDirector] popScene];
	
}


-(void)featureAButtonPressed
{
	NSLog(@"click featureAButtonPressed");
	[self setAllMenuEnabled:NO];
	[[MKStoreManager sharedManager] buyFeatureA];
}

-(void)featureBButtonPressed
{
	
	[self setAllMenuEnabled:NO];
	
	[[MKStoreManager sharedManager] buyFeatureB];
}

-(void)featureCButtonPressed
{
	[self setAllMenuEnabled:NO];
	
	[[MKStoreManager sharedManager] buyFeatureC];
}

-(void)feature1ButtonPressed
{
	[self setAllMenuEnabled:NO];
	
	[[MKStoreManager sharedManager] buyFeature1];
}

-(void)feature2ButtonPressed
{
	[self setAllMenuEnabled:NO];
	
	[[MKStoreManager sharedManager] buyFeature2];
}

-(void)feature3ButtonPressed
{
	[self setAllMenuEnabled:NO];
	
	[[MKStoreManager sharedManager] buyFeature3];
}

- (void)alert:(NSString *)msg
{
    UIAlertView *alertView = [[[UIAlertView alloc] initWithTitle:msg 
														 message:@"" 
														delegate:self 
											   cancelButtonTitle:@"OK" 
											   otherButtonTitles:nil, nil] 
							  autorelease];
	
	[alertView show];
	//[alertView release];
    //[alertView showWithBackground];
}


/*
 处理所有的按钮变灰和还原动作
 */
-(void)setAllMenuEnabled:(BOOL)enabled
{
	static bool last_value=YES;
	
	bool bEn=enabled;
	
	if (last_value == bEn) {
		return;
	}
	
	CGSize winSize=[[CCDirector sharedDirector] winSize];
	
	if (!bEn) {
		///disable the button ,cover by a new layer
        ccColor4B color=ccc4(0, 0, 0, 150);
        CGSize s = [[CCDirector sharedDirector] winSize]; 
		CCLayerColor * layer = [[CCLayerColor alloc] initWithColor:color width:s.width height:s.height];//看看这个函数的文档
		[self addChild:layer z:10 tag:IAP_COVER_LAYER_TAG];
        
		
		// Add the UIActivityIndicatorView (in UIKit universe)
		
		self.activityIndicatorView = [[[UIActivityIndicatorView alloc] 
									   initWithActivityIndicatorStyle: 
									   UIActivityIndicatorViewStyleWhiteLarge] autorelease];
		
		activityIndicatorView.center = ccp(winSize.width/2,winSize.height/2);  //这里是以UIView的框架来显示的，所以要按UIView的坐标系
        //activityIndicatorView.center = ccp(winSize.width/2,winSize.height/2);
		//activityIndicatorView.center = ccp(190,240);
		
        [activityIndicatorView startAnimating];
		
        //[self.view addSubview: activityIndicatorView];
		//[self  addSubview: activityIndicatorView];
		///很强悍的代码，在cocos2d中加入UIciew的空间，哈哈
		[[[CCDirector sharedDirector] openGLView] addSubview:activityIndicatorView];
		
	}
	else {
		CCLOG(@"anc 111");
		/////恢复背景显示，使按钮可点
		if ([self getChildByTag:IAP_COVER_LAYER_TAG] != nil) {
			CCLOG(@"anc 222");
			[[self getChildByTag:IAP_COVER_LAYER_TAG] setVisible:NO];
			CCLOG(@"anc 333");
			[self removeChildByTag:IAP_COVER_LAYER_TAG cleanup:YES];
			CCLOG(@"anc 444");
		}
        
		
		CCLOG(@"anc 555000");
		if(self.activityIndicatorView != nil){
			CCLOG(@"anc 555");
            CCLOG(@"anc 666");
            [self.activityIndicatorView removeFromSuperview];  //// 移动菊花图标
            self.activityIndicatorView =nil; 
            CCLOG(@"anc 777");
			
		}
	}
    
    
	[self setIsTouchEnabled:bEn];
	
	/////////////////////////////////////////////菜单enable or disable
	/////使iap菜单可以点击或者不可以点击
	for (int i=0; i<IAP_MENU_ITEM_IAP_MAX; i++) {
		CCLOG(@"anc 888,%d",i);
		[[menuItemArray objectAtIndex:i] setIsEnabled:bEn];
	}
    
	/////使back menu菜单可以点击或者不可以点击
	/////back menu
	[back setIsEnabled:bEn];
	
	CCLOG(@"anc 999");
    
	last_value=bEn;
}

- (void)productAPurchased
{
	NSLog(@"productAPurchased call back");
	
	
    
	[self setAllMenuEnabled:YES];
	///购买成功 回调 函数
	///弹出用户的金币+1000的提示
	
	player_money+=1000;
	
	NSString * str=[NSString stringWithFormat:@"your coin number has been increased from %d to %d\n"
					,player_money-1000,player_money];
	[self alert:str];
}

- (void)productBPurchased
{
	NSLog(@"productBPurchased call back");
	
	
	
	[self setAllMenuEnabled:YES];
	///购买成功 回调 函数
	///弹出用户的金币+1000的提示
	
	player_money+=5000;
	
	NSString * str=[NSString stringWithFormat:@"your coin number has been increased from %d to %d\n"
					,player_money-5000,player_money];
	[self alert:str];
}

- (void)productCPurchased
{
	NSLog(@"productCPurchased call back");
	
	
	
	[self setAllMenuEnabled:YES];
	///购买成功 回调 函数
	///弹出用户的金币+1000的提示
	
	player_money+=10000;
	
	NSString * str=[NSString stringWithFormat:@"your coin number has been increased from %d to %d\n"
					,player_money-10000,player_money];
	[self alert:str];
}

- (void)product1Purchased
{
	///购买成功 回调 函数
	///弹出用户的等级＋1的提示
	
	NSLog(@"product1Purchased call back");
	
    
	[self setAllMenuEnabled:YES];
	///购买成功 回调 函数
	///弹出用户的金币+1000的提示
	
	player_level+=1;
	
	NSString * str=[NSString stringWithFormat:@"your grade has been up from %d to %d\n"
					,player_level-1,player_level];
	[self alert:str];
}


- (void)product2Purchased
{
	///购买成功 回调 函数
	///弹出用户的等级＋1的提示
	
	NSLog(@"product2Purchased call back");
	
	
	[self setAllMenuEnabled:YES];
	///购买成功 回调 函数
	///弹出用户的金币+1000的提示
	
	player_level+=3;
	
	NSString * str=[NSString stringWithFormat:@"your grade has been up from %d to %d\n"
					,player_level-3,player_level];
	[self alert:str];
}


- (void)product3Purchased
{
	///购买成功 回调 函数
	///弹出用户的等级＋1的提示
	
	NSLog(@"product3Purchased call back");
	
	
	[self setAllMenuEnabled:YES];
	///购买成功 回调 函数
	///弹出用户的金币+1000的提示
	
	player_level+=10;
	
	NSString * str=[NSString stringWithFormat:@"your grade has been up from %d to %d\n"
					,player_level-10,player_level];
	[self alert:str];
}

- (void)failed
{
	//NSString * str=[NSString stringWithFormat:@"purchase Faild!\n"];
	//[self alert:str];
	CCLOG(@"product failed");
	[self setAllMenuEnabled:YES];
}




//////////////////////////////////////////////ad begin
#pragma AD begin
- (void)onEnter
{
	[super onEnter];
	
	adController = [[AdViewController alloc] initWithMasterView:[[CCDirector sharedDirector] openGLView]];
	[adController setDelegate:self];
	
}

- (void)onExit
{
	//Completely remove the controller
	[adController setDelegate:nil];
	[adController release];
	adController = nil;
	
	[super onExit];
}

- (void)adController:(AdViewController*)controller didLoadiAd:(id)iadBanner;
{
	//Do something when the ad loads, like moving objects.
    CCSprite * ad_bg=[self getChildByTag:1001];
    ad_bg.visible=true;
}

- (void)adController:(AdViewController*)controller didFailedToRecieveiAd:(id)iadBanner;
{
	//Do something when the ad fails to load, like moving objects.;
    CCSprite * ad_bg=[self getChildByTag:1001];
    ad_bg.visible=false;
}

- (void)adController:(AdViewController*)controller didLoadAdMobAd:(GADBannerView*)adMobBanner
{
	//Do something when the ad loads, like moving objects.
    CCSprite * ad_bg=[self getChildByTag:1001];
    ad_bg.visible=true;
}

- (void)adController:(AdViewController*)controller didFailedToRecieveAdMobAd:(GADBannerView*)adMobBanner
{
	//Do something when the ad fails to load, like moving objects.
    CCSprite * ad_bg=[self getChildByTag:1001];
    ad_bg.visible=false;
}

//////////////////////////////ad end



#pragma mark resize image

/*
 对UIImage进行缩放的函数
 */
-(UIImage *)resizeImage:(UIImage *)image andScaleX:(float)scaleX andScaleY:(float)scaleY
{
    // original
    //UIImage *image = [UIImage imageNamed:@"icon.png"];
    
    CGRect newRect;
    newRect.size.height = image.size.height*scaleY;
    newRect.size.width = image.size.width*scaleX;
    newRect.origin = (CGPoint){0.0f, 0.0f};
    UIGraphicsBeginImageContext(newRect.size);
    [image drawInRect:newRect];
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    //使用 newImage 即可
    return newImage;
}


@end

/////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////
